<?php
class StaticController extends BaseController {
    /**
     * 获取审核趋势数据
     * @param {string} params.timeRange - 时间范围（today/yesterday/7days/30days/custom）
     * @param {string} params.startDate - 自定义开始日期（当timeRange=custom时必填）
     * @param {string} params.endDate - 自定义结束日期（当timeRange=custom时必填）
     * @param {string} params.period - 周期（day/week/month，默认day）
     * @returns {Promise<Object>} 包含时间节点和对应审核量的对象
     */
    function actionGetAuditTrend() {
        $timeRange = (string)arg("timeRange", "30days");
        $period = (string)arg("period", "day");
        $startDate = (string)arg("startDate", "");
        $endDate = (string)arg("endDate", "");

        // 验证时间范围参数
        $validRanges = ['today', 'yesterday', '7days', '30days', 'custom'];
        if (!in_array($timeRange, $validRanges)) {
            error("无效的时间范围参数");
        }

        // 验证周期参数
        $validPeriods = ['day', 'week', 'month'];
        if (!in_array($period, $validPeriods)) {
            error("无效的周期参数（仅支持day/week/month）");
        }

        // 处理时间范围
        list($start, $end) = $this->handleTimeRange($timeRange, $startDate, $endDate);

        // 根据周期生成时间节点和查询SQL
        $timeField = "DATE_FORMAT(submit_time, '%Y-%m-%d')"; // 默认按日
        $groupBy = "DATE_FORMAT(submit_time, '%Y-%m-%d')";
        $format = 'Y-m-d';

        if ($period === 'week') {
            $timeField = "CONCAT(YEAR(submit_time), 'W', WEEK(submit_time))";
            $groupBy = $timeField;
            $format = 'YW';
        } elseif ($period === 'month') {
            $timeField = "DATE_FORMAT(submit_time, '%Y-%m')";
            $groupBy = $timeField;
            $format = 'Y-m';
        }

        // 查询审核量（合并媒体、言论、合集等类型）
        $sql = "SELECT 
                    $timeField AS time_node,
                    COUNT(*) AS audit_count
                FROM (
                    SELECT submit_time FROM au_media_content 
                    UNION ALL 
                    SELECT submit_time FROM au_comment_content
                    UNION ALL
                    SELECT submit_time FROM au_content_collection
                ) AS all_audit
                WHERE submit_time BETWEEN '$start' AND '$end'
                GROUP BY $groupBy
                ORDER BY time_node ASC";

        $model = new Model(); // 假设存在基础模型类
        $trendData = $model->query($sql);

        // 格式化返回数据
        $result = [
            'time_nodes' => array_column($trendData, 'time_node'),
            'audit_counts' => array_column($trendData, 'audit_count')
        ];

        success($result);
    }

    /**
     * 处理时间范围参数
     * @param string $timeRange 时间范围标识
     * @param string $startDate 自定义开始日期
     * @param string $endDate 自定义结束日期
     * @return array [start, end]
     */
    private function handleTimeRange($timeRange, $startDate, $endDate) {
        $end = date('Y-m-d H:i:s');
        $start = '';

        switch ($timeRange) {
            case 'today':
                $start = date('Y-m-d 00:00:00');
                break;
            case 'yesterday':
                $start = date('Y-m-d 00:00:00', strtotime('-1 day'));
                $end = date('Y-m-d 23:59:59', strtotime('-1 day'));
                break;
            case '7days':
                $start = date('Y-m-d 00:00:00', strtotime('-6 day'));
                break;
            case '30days':
                $start = date('Y-m-d 00:00:00', strtotime('-29 day'));
                break;
            case 'custom':
                if (empty($startDate) || empty($endDate)) {
                    error("自定义时间范围需传入startDate和endDate");
                }
                $start = $startDate . ' 00:00:00';
                $end = $endDate . ' 23:59:59';
                break;
        }

        return [$start, $end];
    }
    /**
     * 获取审核结果分布数据
     * @param {string} params.timeRange - 时间范围（同趋势接口）
     * @param {string} params.startDate - 自定义开始日期
     * @param {string} params.endDate - 自定义结束日期
     * @returns {Promise<Object>} 包含结果类型和对应数量的对象
     */
    function actionGetAuditResultDistribution() {
        $timeRange = (string)arg("timeRange", "30days");
        $startDate = (string)arg("startDate", "");
        $endDate = (string)arg("endDate", "");

        // 处理时间范围
        list($start, $end) = $this->handleTimeRange($timeRange, $startDate, $endDate);

        // 审核结果映射（统一各表状态值）
        $resultMap = [
            'pending' => ['name' => '待审核', 'status' => '1'],
            'passed' => ['name' => '审核通过', 'status' => '2'],
            'rejected' => ['name' => '审核拒绝', 'status' => '31,32,33,34'],
            'review' => ['name' => '再次审核', 'status' => '4']
        ];

        $distribution = [];
        $model = new Model();

        // 统计各结果数量（合并多表）
        foreach ($resultMap as $key => $item) {
            $sql = "SELECT COUNT(*) AS total FROM (
                SELECT audit_status FROM au_media_content 
                WHERE audit_status IN ({$item['status']}) AND submit_time BETWEEN '$start' AND '$end'
                UNION ALL
                SELECT audit_status FROM au_comment_content 
                WHERE audit_status IN ({$item['status']}) AND submit_time BETWEEN '$start' AND '$end'
                UNION ALL
                SELECT audit_status FROM au_content_collection 
                WHERE audit_status IN ({$item['status']}) AND submit_time BETWEEN '$start' AND '$end'
            ) AS all_results";

            $data = $model->query($sql);
            $distribution[] = [
                'name' => $item['name'],
                'value' => (int)($data[0]['total'] ?? 0)
            ];
        }

        success($distribution);
    }
    /**
     * 获取内容类型分布数据
     * @param {string} params.timeRange - 时间范围（同趋势接口）
     * @param {string} params.startDate - 自定义开始日期
     * @param {string} params.endDate - 自定义结束日期
     * @returns {Promise<Object>} 包含内容类型和对应数量的对象
     */
    function actionGetContentTypeDistribution() {
        $timeRange = (string)arg("timeRange", "30days");
        $startDate = (string)arg("startDate", "");
        $endDate = (string)arg("endDate", "");

        // 处理时间范围
        list($start, $end) = $this->handleTimeRange($timeRange, $startDate, $endDate);

        // 内容类型映射
        $typeMap = [
            1 => '图片',
            2 => '视频',
            3 => '音频',
            4 => '文档',
            5 => '言论',
            6 => '合集'
        ];

        $distribution = [];
        $model = new Model();

        // 媒体内容类型
        $sqlMedia = "SELECT content_type, COUNT(*) AS total 
                    FROM au_media_content 
                    WHERE submit_time BETWEEN '$start' AND '$end'
                    GROUP BY content_type";
        $mediaData = $model->query($sqlMedia);

        // 补充言论和合集类型
        $sqlComment = "SELECT 5 AS content_type, COUNT(*) AS total 
                    FROM au_comment_content 
                    WHERE submit_time BETWEEN '$start' AND '$end'";
        $commentData = $model->query($sqlComment);

        $sqlCollection = "SELECT 6 AS content_type, COUNT(*) AS total 
                        FROM au_content_collection 
                        WHERE submit_time BETWEEN '$start' AND '$end'";
        $collectionData = $model->query($sqlCollection);

        // 合并数据
        $allData = array_merge($mediaData, $commentData, $collectionData);
        foreach ($allData as $item) {
            $type = (int)$item['content_type'];
            if (isset($typeMap[$type])) {
                $distribution[] = [
                    'name' => $typeMap[$type],
                    'value' => (int)$item['total']
                ];
            }
        }

        success($distribution);
    }
    /**
     * 获取敏感内容类型分布数据（基于au_media_content表结构）
     * @param {string} params.timeRange - 时间范围
     * @param {string} params.startDate - 自定义开始日期
     * @param {string} params.endDate - 自定义结束日期
     * @returns {Promise<Object>} 包含敏感类型和对应数量的对象
     */
    function actionGetSensitiveTypeDistribution() {
        $timeRange = (string)arg("timeRange", "30days");
        $startDate = (string)arg("startDate", "");
        $endDate = (string)arg("endDate", "");

        // 处理时间范围
        list($start, $end) = $this->handleTimeRange($timeRange, $startDate, $endDate);

        // 敏感类型映射（与敏感词表的word_type对应）
        $sensitiveTypeMap = [
            1 => '政治敏感',
            2 => '色情低俗',
            3 => '暴力恐怖',
            4 => '谣言虚假',
            5 => '广告营销',
            6 => '其他违规'
        ];

        $distribution = [];
        $model = new Model();

        // 查询包含敏感内容的媒体记录
        $sql = "SELECT id, illegal_details 
                FROM au_media_content 
                WHERE is_illegal = 1  -- 仅包含敏感词的内容
                AND submit_time BETWEEN '$start' AND '$end'
                AND illegal_details IS NOT NULL 
                AND illegal_details != ''";

        $mediaData = $model->query($sql);
        $typeCount = array_fill_keys(array_keys($sensitiveTypeMap), 0);

        // 解析每条记录的敏感词详情
        foreach ($mediaData as $item) {
            // illegal_details是JSON格式，示例: [{"word":"敏感词1","type":2},{"word":"敏感词2","type":5}]
            $illegalDetails = json_decode($item['illegal_details'], true);
            
            if (json_last_error() === JSON_ERROR_NONE && is_array($illegalDetails)) {
                // 提取该内容包含的所有敏感类型
                $contentTypes = [];
                foreach ($illegalDetails as $detail) {
                    if (isset($detail['type']) && is_numeric($detail['type'])) {
                        $type = (int)$detail['type'];
                        if (isset($sensitiveTypeMap[$type])) {
                            $contentTypes[$type] = true; // 去重，同一内容的同一类型只算一次
                        }
                    }
                }
                
                // 统计类型数量
                foreach (array_keys($contentTypes) as $type) {
                    $typeCount[$type]++;
                }
            }
        }

        // 格式化结果
        foreach ($typeCount as $type => $count) {
            if ($count > 0) {
                $distribution[] = [
                    'name' => $sensitiveTypeMap[$type],
                    'value' => $count
                ];
            }
        }

        // 补充：如果没有敏感词详情，根据审核拒绝原因统计
        if (empty($distribution)) {
            $sqlFallback = "SELECT 
                            CASE 
                                WHEN audit_status = 32 THEN 1  -- 拒绝-涉政
                                WHEN audit_status = 31 THEN 2  -- 拒绝-涉黄
                                WHEN audit_status = 33 THEN 5  -- 拒绝-广告
                                WHEN audit_status = 34 THEN 6  -- 拒绝-其他
                                ELSE 6 
                            END AS word_type,
                            COUNT(*) AS total
                        FROM au_media_content 
                        WHERE submit_time BETWEEN '$start' AND '$end'
                        AND audit_status IN (31,32,33,34)  -- 仅统计被拒绝的违规内容
                        GROUP BY word_type";

            $fallbackData = $model->query($sqlFallback);
            foreach ($fallbackData as $item) {
                $type = (int)$item['word_type'];
                $distribution[] = [
                    'name' => $sensitiveTypeMap[$type],
                    'value' => (int)$item['total']
                ];
            }
        }

        success($distribution);
    }
    /**
     * 获取审核员工作表现数据
     * @param {string} params.timeRange - 时间范围（同趋势接口）
     * @param {string} params.startDate - 自定义开始日期
     * @param {string} params.endDate - 自定义结束日期
     * @param {number} params.page - 页码
     * @param {number} params.pageSize - 每页条数
     * @returns {Promise<Object>} 包含审核员表现数据和分页信息的对象
     */
    function actionGetAuditorPerformance() {
        $timeRange = (string)arg("timeRange", "30days");
        $startDate = (string)arg("startDate", "");
        $endDate = (string)arg("endDate", "");
        $pagenum = (int)arg("page", 1);
        $pagesize = (int)arg("pageSize", 10);

        // 处理时间范围
        list($start, $end) = $this->handleTimeRange($timeRange, $startDate, $endDate);

        // 计算分页
        $startPage = ($pagenum - 1) * $pagesize;

        // 查询审核员列表
        $auditorModel = new Auditor();
        $auditors = $auditorModel->query("SELECT id, real_name FROM au_auditor WHERE status = 1");

        $performanceList = [];
        $model = new Model();

        foreach ($auditors as $auditor) {
            $auditorId = $auditor['id'];
            $auditorName = $auditor['real_name'];

            // 1. 完成量（已审核的内容总数）
            $totalSql = "SELECT COUNT(*) AS total FROM (
                SELECT 1 FROM au_media_content 
                WHERE auditor_id = $auditorId AND audit_time BETWEEN '$start' AND '$end'
                UNION ALL
                SELECT 1 FROM au_comment_content 
                WHERE auditor_id = $auditorId AND audit_time BETWEEN '$start' AND '$end'
                UNION ALL
                SELECT 1 FROM au_content_collection 
                WHERE auditor_id = $auditorId AND audit_time BETWEEN '$start' AND '$end'
            ) AS total_audit";
            $totalData = $model->query($totalSql);
            $total = (int)($totalData[0]['total'] ?? 0);
            if ($total <= 0) continue;

            // 2. 通过量
            $passedSql = "SELECT COUNT(*) AS passed FROM (
                SELECT 1 FROM au_media_content 
                WHERE auditor_id = $auditorId AND audit_status = 2 AND audit_time BETWEEN '$start' AND '$end'
                UNION ALL
                SELECT 1 FROM au_comment_content 
                WHERE auditor_id = $auditorId AND audit_status = 2 AND audit_time BETWEEN '$start' AND '$end'
                UNION ALL
                SELECT 1 FROM au_content_collection 
                WHERE auditor_id = $auditorId AND audit_status = 2 AND audit_time BETWEEN '$start' AND '$end'
            ) AS passed_audit";
            $passedData = $model->query($passedSql);
            $passed = (int)($passedData[0]['passed'] ?? 0);

            // 3. 拒绝量
            $rejectedSql = "SELECT COUNT(*) AS rejected FROM (
                SELECT 1 FROM au_media_content 
                WHERE auditor_id = $auditorId AND audit_status IN (31,32,33,34) AND audit_time BETWEEN '$start' AND '$end'
                UNION ALL
                SELECT 1 FROM au_comment_content 
                WHERE auditor_id = $auditorId AND audit_status IN (31,32,33,34) AND audit_time BETWEEN '$start' AND '$end'
                UNION ALL
                SELECT 1 FROM au_content_collection 
                WHERE auditor_id = $auditorId AND audit_status IN (31,32,33,34) AND audit_time BETWEEN '$start' AND '$end'
            ) AS rejected_audit";
            $rejectedData = $model->query($rejectedSql);
            $rejected = (int)($rejectedData[0]['rejected'] ?? 0);

            // 4. 平均处理时间（分钟）
            $avgTimeSql = "SELECT AVG(TIMESTAMPDIFF(MINUTE, submit_time, audit_time)) AS avg_time FROM (
                SELECT submit_time, audit_time FROM au_media_content 
                WHERE auditor_id = $auditorId AND audit_time BETWEEN '$start' AND '$end'
                UNION ALL
                SELECT submit_time, audit_time FROM au_comment_content 
                WHERE auditor_id = $auditorId AND audit_time BETWEEN '$start' AND '$end'
                UNION ALL
                SELECT submit_time, audit_time FROM au_content_collection 
                WHERE auditor_id = $auditorId AND audit_time BETWEEN '$start' AND '$end'
            ) AS time_audit";
            $avgTimeData = $model->query($avgTimeSql);
            $avgTime = round((float)($avgTimeData[0]['avg_time'] ?? 0), 2);

            // 5. 准确率（假设以复查通过为基准，这里简化为通过/(通过+拒绝)）
            $accuracy = $total > 0 ? round(($passed / $total) * 100, 2) : 0;

            $performanceList[] = [
                'auditor_name' => $auditorName,
                'completed' => $total,
                'passed' => $passed,
                'rejected' => $rejected,
                'avg_process_time' => $avgTime,
                'accuracy' => $accuracy . '%'
            ];
        }

        // 分页处理
        $total = count($performanceList);
        $list = array_slice($performanceList, $startPage, $pagesize);

        success([
            'list' => $list,
            'total' => $total,
            'page' => $pagenum,
            'pageSize' => $pagesize
        ]);
    }
    
    /**
     * 审核统计数据导出接口
     * 支持导出审核趋势、结果分布、内容类型分布、敏感内容分布和审核员表现数据
     */
    function actionExportData() {
        // 获取请求参数
        $timeRange = (string)arg("timeRange", "30days");
        $startDate = (string)arg("startDate", "");
        $endDate = (string)arg("endDate", "");
        $contentType = (string)arg("contentType", "all");
        $exportType = (string)arg("exportType", "all"); // all/trend/result/type/sensitive/auditor
        
        // 处理时间范围
        list($start, $end) = $this->handleTimeRange($timeRange, $startDate, $endDate);
        
        // 设置响应头，告知浏览器这是Excel文件
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="审核统计数据_' . date('YmdHis') . '.xls"');
        header('Cache-Control: max-age=0');
        
        // 创建一个文件句柄
        $fp = fopen('php://output', 'a');
        
        // 设置Excel表头编码
        $title = "审核统计数据（{$start}至{$end}）";
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF)); // UTF-8 BOM，解决中文乱码
        fputcsv($fp, array($title), "\t");
        fputcsv($fp, array(''), "\t"); // 空行分隔
        
        // 根据导出类型处理
        switch ($exportType) {
            case 'trend':
                $this->exportAuditTrend($fp, $start, $end, $contentType);
                break;
            case 'result':
                $this->exportAuditResult($fp, $start, $end, $contentType);
                break;
            case 'type':
                $this->exportContentType($fp, $start, $end, $contentType);
                break;
            case 'sensitive':
                $this->exportSensitiveType($fp, $start, $end, $contentType);
                break;
            case 'auditor':
                $this->exportAuditorPerformance($fp, $start, $end);
                break;
            default:
                // 导出全部数据
                $this->exportAuditTrend($fp, $start, $end, $contentType);
                $this->exportAuditResult($fp, $start, $end, $contentType);
                $this->exportContentType($fp, $start, $end, $contentType);
                $this->exportSensitiveType($fp, $start, $end, $contentType);
                $this->exportAuditorPerformance($fp, $start, $end);
        }
        
        fclose($fp);
        exit;
    }

    /**
     * 导出审核趋势数据
     */
    private function exportAuditTrend($fp, $start, $end, $contentType) {
        fputcsv($fp, array('审核趋势数据'), "\t");
        fputcsv($fp, array('时间节点', '审核总量', '通过量', '拒绝量'), "\t");
        
        $model = new Model();
        
        // 按日统计
        $sql = "SELECT 
                    DATE_FORMAT(submit_time, '%Y-%m-%d') AS time_node,
                    COUNT(*) AS total,
                    SUM(CASE WHEN audit_status = 2 THEN 1 ELSE 0 END) AS passed,
                    SUM(CASE WHEN audit_status IN (31,32,33,34) THEN 1 ELSE 0 END) AS rejected
                FROM au_media_content
                WHERE submit_time BETWEEN '$start' AND '$end'
                " . ($contentType != 'all' ? "AND content_type = " . (int)$contentType : "") . "
                GROUP BY time_node
                ORDER BY time_node ASC";
        
        $data = $model->query($sql);
        foreach ($data as $row) {
            fputcsv($fp, array(
                $row['time_node'],
                $row['total'],
                $row['passed'],
                $row['rejected']
            ), "\t");
        }
        
        fputcsv($fp, array(''), "\t"); // 空行分隔
    }

    /**
     * 导出审核结果分布数据
     */
    private function exportAuditResult($fp, $start, $end, $contentType) {
        fputcsv($fp, array('审核结果分布数据'), "\t");
        fputcsv($fp, array('结果类型', '数量', '占比'), "\t");
        
        $model = new Model();
        
        // 总数量
        $totalSql = "SELECT COUNT(*) AS total 
                    FROM au_media_content
                    WHERE submit_time BETWEEN '$start' AND '$end'
                    " . ($contentType != 'all' ? "AND content_type = " . (int)$contentType : "");
        $totalData = $model->query($totalSql);
        $total = (int)($totalData[0]['total'] ?? 0);
        
        // 各状态数量
        $sql = "SELECT 
                    CASE 
                        WHEN audit_status = 1 THEN '待审核'
                        WHEN audit_status = 2 THEN '审核通过'
                        WHEN audit_status = 31 THEN '拒绝-涉黄'
                        WHEN audit_status = 32 THEN '拒绝-涉政'
                        WHEN audit_status = 33 THEN '拒绝-广告'
                        WHEN audit_status = 34 THEN '拒绝-其他'
                        WHEN audit_status = 4 THEN '再次审核'
                        ELSE '未知状态'
                    END AS status_name,
                    COUNT(*) AS count
                FROM au_media_content
                WHERE submit_time BETWEEN '$start' AND '$end'
                " . ($contentType != 'all' ? "AND content_type = " . (int)$contentType : "") . "
                GROUP BY audit_status
                ORDER BY count DESC";
        
        $data = $model->query($sql);
        foreach ($data as $row) {
            $percentage = $total > 0 ? round(($row['count'] / $total) * 100, 2) . '%' : '0%';
            fputcsv($fp, array(
                $row['status_name'],
                $row['count'],
                $percentage
            ), "\t");
        }
        
        fputcsv($fp, array(''), "\t"); // 空行分隔
    }

    /**
     * 导出内容类型分布数据
     */
    private function exportContentType($fp, $start, $end, $contentType) {
        fputcsv($fp, array('内容类型分布数据'), "\t");
        fputcsv($fp, array('内容类型', '数量', '占比'), "\t");
        
        $model = new Model();
        
        // 总数量
        $totalSql = "SELECT COUNT(*) AS total 
                    FROM au_media_content
                    WHERE submit_time BETWEEN '$start' AND '$end'
                    " . ($contentType != 'all' ? "AND content_type = " . (int)$contentType : "");
        $totalData = $model->query($totalSql);
        $total = (int)($totalData[0]['total'] ?? 0);
        
        // 各类型数量
        $sql = "SELECT 
                    CASE 
                        WHEN content_type = 1 THEN '图片'
                        WHEN content_type = 2 THEN '视频'
                        WHEN content_type = 3 THEN '音频'
                        WHEN content_type = 4 THEN '文档'
                        ELSE '未知类型'
                    END AS type_name,
                    COUNT(*) AS count
                FROM au_media_content
                WHERE submit_time BETWEEN '$start' AND '$end'
                " . ($contentType != 'all' ? "AND content_type = " . (int)$contentType : "") . "
                GROUP BY content_type
                ORDER BY count DESC";
        
        $data = $model->query($sql);
        foreach ($data as $row) {
            $percentage = $total > 0 ? round(($row['count'] / $total) * 100, 2) . '%' : '0%';
            fputcsv($fp, array(
                $row['type_name'],
                $row['count'],
                $percentage
            ), "\t");
        }
        
        fputcsv($fp, array(''), "\t"); // 空行分隔
    }

    /**
     * 导出敏感内容类型分布数据
     */
    private function exportSensitiveType($fp, $start, $end, $contentType) {
        fputcsv($fp, array('敏感内容类型分布数据'), "\t");
        fputcsv($fp, array('敏感类型', '数量', '占比'), "\t");
        
        $model = new Model();
        $sensitiveTypeMap = [
            1 => '政治敏感',
            2 => '色情低俗',
            3 => '暴力恐怖',
            4 => '谣言虚假',
            5 => '广告营销',
            6 => '其他违规'
        ];
        
        // 查询包含敏感内容的媒体记录
        $sql = "SELECT id, illegal_details 
                FROM au_media_content 
                WHERE is_illegal = 1
                AND submit_time BETWEEN '$start' AND '$end'
                AND illegal_details IS NOT NULL 
                AND illegal_details != ''
                " . ($contentType != 'all' ? "AND content_type = " . (int)$contentType : "");
        
        $mediaData = $model->query($sql);
        $typeCount = array_fill_keys(array_keys($sensitiveTypeMap), 0);
        $total = 0;
        
        // 解析敏感词详情并统计
        foreach ($mediaData as $item) {
            $illegalDetails = json_decode($item['illegal_details'], true);
            if (json_last_error() === JSON_ERROR_NONE && is_array($illegalDetails)) {
                $contentTypes = [];
                foreach ($illegalDetails as $detail) {
                    if (isset($detail['type']) && is_numeric($detail['type'])) {
                        $type = (int)$detail['type'];
                        if (isset($sensitiveTypeMap[$type])) {
                            $contentTypes[$type] = true;
                        }
                    }
                }
                foreach (array_keys($contentTypes) as $type) {
                    $typeCount[$type]++;
                    $total++;
                }
            }
        }
        
        // 输出统计结果
        foreach ($typeCount as $type => $count) {
            if ($count > 0) {
                $percentage = $total > 0 ? round(($count / $total) * 100, 2) . '%' : '0%';
                fputcsv($fp, array(
                    $sensitiveTypeMap[$type],
                    $count,
                    $percentage
                ), "\t");
            }
        }
        
        fputcsv($fp, array(''), "\t"); // 空行分隔
    }

    /**
     * 导出审核员表现数据
     */
    private function exportAuditorPerformance($fp, $start, $end) {
        fputcsv($fp, array('审核员工作表现数据'), "\t");
        fputcsv($fp, array('审核员姓名', '总审核量', '通过量', '拒绝量', '平均处理时间(分钟)', '准确率(%)'), "\t");
        
        $model = new Model();
        
        // 查询审核员列表
        $auditorModel = new Auditor();
        $auditors = $auditorModel->query("SELECT id, real_name FROM au_auditor WHERE status = 1");
        
        foreach ($auditors as $auditor) {
            $auditorId = $auditor['id'];
            $auditorName = $auditor['real_name'];
            
            // 统计审核数据
            $sql = "SELECT 
                        COUNT(*) AS total,
                        SUM(CASE WHEN audit_status = 2 THEN 1 ELSE 0 END) AS passed,
                        SUM(CASE WHEN audit_status IN (31,32,33,34) THEN 1 ELSE 0 END) AS rejected,
                        AVG(TIMESTAMPDIFF(MINUTE, submit_time, audit_time)) AS avg_time
                    FROM au_media_content
                    WHERE auditor_id = $auditorId 
                    AND audit_time BETWEEN '$start' AND '$end'";
            
            $data = $model->query($sql);
            $stats = $data[0] ?? [];
            
            $total = (int)($stats['total'] ?? 0);
            if ($total <= 0) continue;
            
            $passed = (int)($stats['passed'] ?? 0);
            $rejected = (int)($stats['rejected'] ?? 0);
            $avgTime = round((float)($stats['avg_time'] ?? 0), 2);
            $accuracy = round(($passed / $total) * 100, 2);
            
            fputcsv($fp, array(
                $auditorName,
                $total,
                $passed,
                $rejected,
                $avgTime,
                $accuracy
            ), "\t");
        }
    }

    
    
}
